<template>
  <div>
    <el-upload v-model:file-list="fileList" :action="url" :data="fileData" :limit="limitImgNumber" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUploadHandle" :on-change="handleFileChange" :on-success="successHandle" :class="{hideAdd:uploadDisabled}">
      <el-icon>
        <Plus />
      </el-icon>

      <template v-slot:tip>
        <div class="el-upload__tip">只支持jpg、png格式文件！</div>
      </template>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, watch } from "vue";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";

const emit = defineEmits(["updatImgList"]);

const props = defineProps({
  urlList: {
    type: Array,
    required: true
  }
});

const url = ref("");
const fileData = ref({
  busType: 0
});
const fileList = ref<IObject[]>([]);
// 控制是否显示图片上传+号
const uploadDisabled = ref<boolean>(false);
// 允许上传图片的数量
const limitImgNumber = ref<number>(1);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const init = () => {
  url.value = `${app.api}/sys/oss/uploadServer?token=${getToken()}`;
  fileList.value = props.urlList as IObject[];
  uploadDisabled.value = fileList.value.length >= limitImgNumber.value;
};

// 上传之前
const beforeUploadHandle = (file: IObject) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png") {
    ElMessage.error("只支持jpg、png格式文件！");
    return false;
  }
};

// 文件上传变化
const handleFileChange = (file: IObject, fileList: IObject[]) => {
  //是否展示图片+号
  uploadDisabled.value = fileList.length >= limitImgNumber.value;
};

// 上传成功
const successHandle = (res: IObject, file: IObject, list: IObject[]) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  fileList.value = [
    {
      name: "轮播图",
      url: res.data.src
    }
  ];
  emit("updatImgList", fileList.value);
};

// 预览
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 删除
const handleRemove: UploadProps["onRemove"] = (file: IObject, fileList: IObject[]) => {
  fileList.value = [];
  emit("updatImgList", fileList.value);
  //手动触发change事件
  handleFileChange(file, fileList);
};

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
:deep .el-upload-dragger {
  border-width: 0px;
}

.hideAdd {
  :deep .el-upload--picture-card {
    display: none;
  }
}

:deep .el-upload-dragger {
  width: 180px;
  height: 180px;
  padding: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>